<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>ajax请求数据</button>
    <script>
       

        function sendAjax(obj) {
            // console.log(obj.url)
            // console.log(obj.method)
            if (obj.method === undefined) {
                obj.method = 'get'
            } else {
                if (obj.method.toLowerCase() != 'get' && obj.method.toLowerCase() != 'post' && obj.method.toLowerCase() != 'put' && obj.method.toLowerCase() != 'delete') {
                    throw new Error('请求方式不正确')
                }
            }
            if (obj.url === undefined) {
                throw new Error('请求地址不能为空')
            } else {
                if (typeof obj.url != 'string') {
                    throw new Error('请求地址不正确！')
                }
            }
            if (obj.async === undefined) {
                obj.async = true
            } else {
                if (typeof obj.async != 'boolean') {
                    throw new Error('async必须的布尔值')
                }
            }
            var xhr = new XMLHttpRequest()
            xhr.open(obj.method, obj.url, obj.async)
            if (obj.data != undefined) {
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                if (typeof obj.data === 'object') {
                    var arr = []
                    for (var key in obj.data) {
                        arr.push(key + '=' + obj.data[key])
                    }
                    xhr.send(arr.join('&'))
                } else {
                    xhr.send(obj.data)
                }

            } else {
                xhr.send()
            }
            if (obj.async === false) {
                var msg = xhr.responeText
                obj.success(msg)
            } else {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            var msg = xhr.responeText
                            obj.success(msg)
                        }
                    }
                }
            }
        }
        document.querySelector('button').onclick =function()
        {
             {
            var obj = {
            method: 'get',
            url: 'http://localhost:3000/users',
            async: '',
            success:''
        };
            sendAjax(obj)
        }
        }
       

    </script>
</body>

</html>